<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>拖拽</title>
    <style>
        * {
            padding: 0;
            margin: 0;
        }

        div {
            width: 100px;
            height: 100px;
            background-color: blueviolet;
            position: absolute;
        }
    </style>
</head>

<body>
    <div>
        <button>回放</button>
    </div>
</body>
<script>
    let div = document.querySelector('div');
    let btn = document.querySelector('button');

    let isok = false;
    let obj = {};
    let num = 0;

    div.onmousedown = (e) => {
        isok = true;
        if (e.target.nodeName == 'DIV') {
            obj = {};
            num = 0;
            obj[num] = [div.offsetLeft, div.offsetTop];
        }
    }

    div.onmouseup = () => isok = false;

    window.onmousemove = (e) => {
        if (isok) {
            num++;
            e = e || window.event;
            let eleX = e.clientX - div.offsetWidth / 2;
            let eleY = e.clientY - div.offsetHeight / 2;
            if (eleX >= window.innerWidth - div.offsetWidth) eleX = window.innerWidth - div.offsetWidth;
            else if (eleX < 0) eleX = 0;
            if (eleY >= window.innerHeight - div.offsetHeight) eleY = window.innerHeight - div.offsetHeight;
            else if (eleY < 0) eleY = 0;
            div.style.left = eleX + 'px';
            div.style.top = eleY + 'px';

            let arr = [];
            for (let j = 0; j < 2; j++) {
                j == 0 ? arr.push(eleX) : arr.push(eleY);
                obj[num] = arr;
            }
        }
    }

    btn.onclick = (e) => {
        delete obj[num];//此处删除是由于检查时发现对象最后面的值与实际不符，故删除;
        let i = 0;
        let timer = setInterval(() => {
            div.style.left = obj[i][0] + 'px';
            div.style.top = obj[i][1] + 'px';
            i++;
            if (i == num) clearInterval(timer);
        }, 30)
    }
</script>

</html>